package cn.easy.rpc.io;

import cn.easy.rpc.config.ConfigHolder;
import cn.easy.rpc.context.RpcContext;
import cn.easy.rpc.core.DataExchangeIdentity;
import lombok.SneakyThrows;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.Socket;

/**
 * @author zwb
 * @create 2020-09-06 17:53
 **/
@Component
public class Registering implements ApplicationListener<ContextRefreshedEvent> {

    public volatile boolean off = false;

    private boolean initialized = false;

    @SneakyThrows
    public void register() {
        final Socket socket =  new Socket(ConfigHolder.serviceCenterHost, ConfigHolder.serviceCenterPort);
        ObjectInputStream is = null;
        ObjectOutputStream os = null;
        //心跳检测
        while (!off) {
            try {
                os = new ObjectOutputStream(socket.getOutputStream());
                try {
                    if(!initialized) {
                        os.writeObject(new DataExchangeIdentity(ConfigHolder.config, null));
                        initialized = true;
                    }else {
                        os.writeObject(new DataExchangeIdentity(null, null));
                    }
                    is = new ObjectInputStream(new BufferedInputStream(
                            socket.getInputStream()));
                    DataExchangeIdentity dataExchangeIdentity = (DataExchangeIdentity)is.readObject();
                    RpcContext.getInstance().setDependService(dataExchangeIdentity.getPong());
                } catch (Exception exception) {
                    //ignore
                }
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
                off = true;
                socket.close();
            }
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ConfigHolder.config.print();
        register();
    }
}
